#include "qbciserial.h"

QBciSerial::QBciSerial(){

}

QBciSerial::~QBciSerial(){

}

void QBciSerial::setPortname(const QString &portname){
    PortName = portname;
}

void QBciSerial::write(const QByteArray &mesg){
    serial->write(mesg);
    serial->waitForBytesWritten();
    qDebug() << "Serial Writed";
}

void QBciSerial::SerialInit(){
    serialThread = new QThread;
    serial = new QSerialPort;
    serial->moveToThread(serialThread);
    connect(serialThread, &QThread::started, this, &QBciSerial::beforeStart);
    connect(serialThread, &QThread::finished, this, &QBciSerial::beforeStop);
}

void QBciSerial::beforeStart() {
  serial->setPortName(PortName);
  serial->setBaudRate(QSerialPort::Baud9600);
  serial->setParity(QSerialPort::NoParity);
  serial->setDataBits(QSerialPort::Data8);
  serial->setStopBits(QSerialPort::OneStop);
  serial->setFlowControl(QSerialPort::NoFlowControl);

  if (serial->open(QIODevice::ReadWrite)) {
      QLogger::Info("UART::Serial opened!");
      qDebug() << "Serial opened";
  } else {
      QLogger::Error("UART::Serial open failed!");
      qDebug() << "Serial failed";
  }
}

void QBciSerial::beforeStop() {
  serial->close();
  serial->deleteLater();
  QLogger::Info("UART::Serial closed!");
}
